<?php defined('SYSPATH') or die('No direct script access.');

/**
 * 课程日志数据模型
 * 
 * @author 陈蕾
 */
class Model_LessonLog extends ORM
{
	const TABLE = 'lesson_log';
	
	// Model table information
    protected $_table_name = 'lesson_log';
    
    // Table primary key and value
	protected $_primary_key  = 'id';
	protected $_primary_val  = 'created';
	
	/**
	 * 计算耗时
	 */
	public function calDuration()
	{
		if (!$this->loaded()) {
			return;
		}
		
		$start = strtotime($this->created);
		$end   = strtotime($this->last_actived);
		
		$this->duration = $end - $start;
	}
	
	/**
	 * 获取课时耗时
	 * 
	 * @param int $member_id 学生ID
	 * @param int $lesson_id 课时ID
	 */
	public static function getTook($member_id, $lesson_id)
	{
		return DB::select('lesson_id', array(DB::expr('SUM(duration)'), 'took'))
			->from(self::TABLE)
			->where('member_id', '=', $member_id)
			->execute()
			->get('took');
	}
	
	/**
	 * 获取耗时统计
	 * 
	 * @param int $member_id 学生ID
	 */
	public static function getTookStats($member_id)
	{
		$records = DB::select('lesson_id', array(DB::expr('SUM(duration)'), 'took'))
			->from(self::TABLE)
			->where('member_id', '=', $member_id)
			->group_by('lesson_id')
			->execute()
			->as_array();
		
		$stats = array();
		foreach ($records as $record) {
			$key = $record['lesson_id'];
			$stats[$key] = $record['took'];
		}
		
		return $stats;
	}
	
	/**
	 * 获取学生的课时学习日志
	 * 
	 * @param int $member_id 学生ID
	 * @param int $lesson_id 课时ID
	 */
	public static function getListByMember($member_id, $lesson_id)
	{
		return DB::select()
			->from(self::TABLE)
			->where('member_id', '=', $member_id)
			->and_where('lesson_id', '=', $lesson_id)
			->order_by('id', 'ASC')
			->execute()
			->as_array();
	}
	
	/**
	 * 获取最后一次学习的日志
	 * 
	 * @param int $member_id 学生ID
	 */
	public static function getLast($member_id)
	{
		$log = DB::select()
			->from(self::TABLE)
			->where('member_id', '=', $member_id)
			->order_by('id', 'DESC')
			->limit(1)
			->execute()
			->current();
		
		if (!$log) {
			return array();
		}
		
		return $log;
	}
}